package org.itboys.admin.service.lasted;

import org.apache.commons.lang3.StringUtils;
import org.itboys.admin.dto.lasted.SystemUserDto;
import org.itboys.admin.entity.lasted.SystemOrg;
import org.itboys.admin.entity.lasted.SystemUser;
import org.itboys.commons.utils.encryption.Digests;
import org.itboys.commons.utils.io.FileUtils;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.itboys.param.PageResult;
import org.itboys.param.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 作者：jiangxiong
 * 日期：2017年2月27日
 * 联系方式 ：empty90911@126.com
 * 描述：系统_用户_Service，江雄重新写的
 */
@Service
public class SystemUserService extends BaseMongoService<SystemUser> {
    @Autowired
    private SystemOrgService orgService;


    @Autowired
    private ResourceHolder resourceHolder;



    @Resource(name = "adminDS")
    private MongoDataSource ds;

    @Override
    protected MongoDataSource getMongoDataSource() {
        return ds;
    }

    @Override
    protected Class<SystemUser> getEntityClass() {
        return SystemUser.class;
    }
    /**
     * 修改或新增
     * @param user
     */
    public Integer saveUser(SystemUser user,MultipartFile logoFile) throws  Exception{
        //不允许添加超级用户
        user.setIsSuper(0);
        //保存头像
        if(logoFile!=null&&!logoFile.isEmpty()){
            String savePath =resourceHolder.getStringValue("fileUploadPath");
            String oldName = logoFile.getOriginalFilename();
            String filePath = FileUtils.saveFile(logoFile.getInputStream(), savePath, oldName, logoFile.getContentType());
            user.setLogo(filePath);
        }
        Map<String,Object> param = new HashMap<String,Object>();
        if(user.getId()==0l){
            //校验用户名称是否存在
            param.clear();
            param.put("userName",user.getUserName());
            if(ListUtil.isNotNull(super.list(param))){
               return -2;
            }
            user.setPassword(Digests.md5(user.getPassword()));
            super.save(user);
        }else{
            param.clear();
            param.put("userName",user.getUserName());
            param.put("id !=",user.getId());

            if(ListUtil.isNotNull(super.list(param))){
                return -2;
            }
            if(StringUtils.isNotEmpty(user.getPassword())){
                user.setPassword(Digests.md5(user.getPassword()));
            }

            super.updateExceptEmpty(user.getId(),user);
        }
        return 0;
    }

    /**
     * 分页获取
     * @param request
     * @return
     */
    public PageResult<SystemUserDto> selectUser(HttpServletRequest request){
        Map<String,Object> param =ParamUtil.packageMongoExactParam(request,"status","orgId");
        param.put("isDeleted", 0);
        Map<String,String> containsparam = ParamUtil.packageMongoVagueParam(request,"name","userName");
        PageResult<SystemUser> result=super.containpageQuery(request,containsparam,param);
       // logger.info("-----------------");
        return new PageResult<SystemUserDto>(packageDtoMuilt(result.getData()),result.getTotal());
    }
    /**
     * 单个查询
     * @param id
     * @return
     */
    public  SystemUserDto findOne(Long id){
       if(LongUtil.isNotZreo(id)){
           return packageDtoSingle(super.getById(id),null);
       }else{
           SystemUserDto dto = new SystemUserDto();
           dto.setId(0l);
           return dto;

       }

    }
    /**
     * 单个查询
     * @param userName
     * @return
     */
    public  SystemUser findOne(String userName){
        if(StringUtils.isEmpty(userName))return null;
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("userName",userName);
        param.put("isDeleted",0);
        List<SystemUser> users = super.list(param);
        if(ListUtil.isNotNull(users)){
            return users.get(0);
        }
        return null;

    }
    /**
     * 修改密码
     * @param id
     * @param oldPassword
     * @param newPassword
     * @return
     * @throws Exception
     */
    public Integer updatePassword(Long id,String oldPassword,String newPassword) throws  Exception{
        SystemUser user = super.getById(id);
        if(!Digests.md5(oldPassword).equalsIgnoreCase(user.getPassword())){
            return -2;//旧密码错误
        }
        super.update(id,"password",Digests.md5(newPassword));
        return 0;
    }

    /**
     * 修改个人信息
     * @param id
     * @param name
     * @param mobile
     * @param email
     */
    public void updateUser(Long id,String name,String mobile,String email){
        SystemUser user =new SystemUser();
        user.setId(id);

        user.setName(name);
        user.setMobile(mobile);
        user.setEmail(email);
        super.updateExceptEmpty(id,user);
    }

    /*********************************组装dto*****************************************/
    public SystemUserDto packageDtoSingle(SystemUser user, SystemOrg org/*, SystemUser creator, SystemUser updater*/) {
        String imageRoot=resourceHolder.getStringValue("imgRoot");
        String orgName="";
        if(LongUtil.isNotZreo(user.getOrgId())&&org==null){
            org=orgService.getById(user.getOrgId());
            orgName=org.getName();
        }else if(org!=null){
            orgName=org.getName();
        }


        return new SystemUserDto(user.getId(),
                user.getCreator(),
                null,
                user.getCreateTime(),
                user.getCreateDate(),
                user.getUpdater(), null, user.getUpdateTime(), user.getUpdateDate(),
                user.getIsDeleted(), user.getUserName(),   user.getName(),   user.getMobile(),
                user.getEmail(),   user.getStatus(), StringUtils.isNotEmpty(user.getLogo())?imageRoot+user.getLogo():null,
                user.getOrgId(),
                orgName,
                user.getIsSuper());




     }

    public List<SystemUserDto> packageDtoMuilt(List<SystemUser> users) {
        List<SystemUserDto> dtos = new ArrayList<SystemUserDto>();
        Map<String, Object> param = new HashMap<String, Object>();
        List<Long> orgIds = new ArrayList<Long>();
        List<SystemOrg> orgs = new ArrayList<SystemOrg>();
     /*   List<Long> operaterIds= new ArrayList<Long>();
        List<SystemUser> operaters = new ArrayList<SystemUser>();*/
        for(SystemUser user:users){
            if(LongUtil.isNotZreo(user.getOrgId())){
                orgIds.add(user.getOrgId());
            }
          /*  //数据创建者ID
            if(LongUtil.isNotZreo(user.getCreator())){
                operaterIds.add(user.getCreator());

            }
            //数据数据修改者ID
            if(LongUtil.isNotZreo(user.getUpdater())){
                operaterIds.add(user.getUpdater());
            }*/
        }
        //匹配组织
        if(ListUtil.isNotNull(orgIds)){
            param.clear();
            param.put("isDeleted",0);
            param.put("id in",orgIds);
            orgs=orgService.list(param);
        }
        //匹配数据创建者和修改者(通用)
       /* if(ListUtil.isNotNull(operaterIds)){
            param.clear();
            param.put("isDeleted",0);
            param.put("id in",operaterIds);
            operaters=super.list(param);
        }*/







     /*   SystemOrg org=null;
        SystemUser creator=null;
        SystemUser updater=null;
        避免空指针异常*/
        SystemOrg org=new SystemOrg();
        SystemUser creator=new SystemUser();
        SystemUser updater=new SystemUser();
        for(SystemUser user:users){
            for(SystemOrg o:orgs){
                if(LongUtil.isNotZreo(user.getOrgId())&&
                        user.getOrgId().longValue()==o.getId()){
                    org=o;

                    break;
                }
            }
            /*//匹配数据创建者(通用)
            for(SystemUser operater:operaters){
                if(LongUtil.isNotZreo(user.getCreator())&&
                        user.getCreator().longValue()==operater.getId()){

                    creator=operater;
                    break;
                }
            }
            //匹配数据修改者(通用)
            for(SystemUser operater:operaters){
                if(LongUtil.isNotZreo(user.getUpdater())&&
                        user.getUpdater().longValue()==operater.getId()){
                    updater=operater;

                    break;
                }
            }*/
            dtos.add(packageDtoSingle(user,org));
        }




        return dtos;
    }



}
